import math

from django.core.paginator import Paginator
from django.http import JsonResponse
from content.models import *


def getList(page_index, id_, tp):
    allData = None
    # 评论
    if tp == 1:
        allData = Content.objects.filter(art_id=id_).order_by("-createTime")  # 时间降序
    # 回复
    elif tp == 2:
        allData = Reply.objects.filter(content_id=id_).order_by("-createTime")
    allpage = math.ceil(allData.count() / 5)
    paginator = Paginator(allData, 5)  # 每页5条
    return paginator.get_page(page_index), allpage

def format_time(time, fmt="%Y,%m,%d,%H,%M"):
    return time.strftime(fmt)

# 处理数据
def dispost_data(datas,pages,tp):
    data = [{
        "cid":d.id if tp==1 else "",
        "uid": d.contenter.uid if tp==1 else d.replyer.uid,
        "nickname": d.contenter.nickname if tp==1 else d.replyer.nickname,
        "uimg": d.contenter.img.url if tp==1 else d.replyer.img.url,
        "comment": d.comment,
        "time": format_time(d.createTime)
    } for d in datas.object_list]
    return JsonResponse({"statu": True, "datas": data, "pageNum": pages})

# 返回评论内容
def find_content(request):
    index = request.GET.get("index")
    aid = request.GET.get("aid")
    datas, pages = getList(index, aid, 1)
    return dispost_data(datas,pages,1)

# 返回回复内容
def find_reply(request):
    index = request.GET.get("index")
    cid = request.GET.get("cid")
    datas, pages = getList(index, cid, 2)
    return dispost_data(datas,pages,2)

# 发布评论
def add_content(request):
    try:
        if request.method == "POST":
            aid = request.POST.get("aid")
            uid = request.POST.get("uid")
            comment = request.POST.get("comment")
            content = Content(
                contenter_id=uid,
                art_id=aid,
                comment=comment
            )
            content.save()
            return JsonResponse({"statu": True})
    except Exception as e:
        print("content=>views=>add_contet error", e)
        return JsonResponse({"statu": False})


# 回复评论
def add_reply(request):
    try:
        if request.method == "POST":
            uid = request.POST.get("uid")
            cid = request.POST.get("cid")
            comment = request.POST.get("comment")
            reply = Reply(
                content_id=cid,
                replyer_id=uid,
                comment=comment
            )
            reply.save()
            return JsonResponse({"statu": True})
    except Exception as e:
        print("content=>views=>add_reply error", e)
        return JsonResponse({"statu": False})
